package com.hongdee.crm.weChat.service.impl;

import com.hongdee.crm.weChat.dao.ITBcOrganDao;
import com.hongdee.crm.weChat.service.ITBcOrganWechatService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by Liu XiaoLong
 * Date: 2017/10/23.
 * Remark:
 */
@Service
public class WechatTBcOrganServiceImpl implements ITBcOrganWechatService {

    @Autowired
    private ITBcOrganDao itBcOrganDao;
    private String tableName = "t_bc_organ";
    /**
     * @Name: 获取附近公司列表  根据位置经纬度
     * @Author: Liu XiaoLong
     * @Date: 2017/10/23 15:57
     * @Remark:
     */
    @Override
    public List getOrganByPosition(String uid,String vin,String city,String longtitude,String latitude) throws Exception {

        if(vin.isEmpty()){
            throw new Exception("vin号有误！");
        }
        if(longtitude == "" || longtitude == null){
            longtitude = "0";
        }
        if(latitude == "" || latitude == null){
            latitude = "0";
        }

        double longt = Double.parseDouble(longtitude);
        double latit = Double.parseDouble(latitude);

        List list = new ArrayList();
        boolean preIsEqueals = false;

        Map lastMap = getLastOrgan(vin,city); // 上次回厂保养门店查询
        List ids = new ArrayList(); // ids 用于数据库去重
        List brandCityList;

        if(lastMap.size()>0){ // 此车存在上次保养门店
            list.add(0,lastMap); // 加入上次保养门店
            brandCityList = getBrandCityOrgan(vin,city,lastMap.get("id").toString(),longt,latit);// 在加入同城市同品牌的list （去除以上已加入的list）

            ids.add("'"+lastMap.get("id").toString()+"'"); // 记录已写入的id
            preIsEqueals = false;
        }
        else { // 不存在上次门店
            brandCityList = getBrandCityOrgan(vin,city,"",longt,latit); // 在加入同城市同品牌的list （去除以上已加入的list）
            preIsEqueals = true;
        }



        if(brandCityList.size()>0){
            // 遍历将结果放入list
            for(int i = 0;i<brandCityList.size();i++){
                list.add(brandCityList.get(i));
                if(i == 0 & preIsEqueals){
                    ids.add("'"+((Map)brandCityList.get(i)).get("id")+"'"); // 记录已写入的id
                }
                else {
                    ids.add(",'"+((Map)brandCityList.get(i)).get("id")+"'"); // 记录已写入的id
                }
            }
            //preIsEqueals = false;
        }
        else {
            if(preIsEqueals == true){
                preIsEqueals = true;
            }

        }

        // 在加入同城市非同品牌的list（去除以上已加入的list）
        List unequealBrandCityList = getCityAndUnequalBrandOrgan(city,ids,longt,latit);

            for(int i = 0;i<unequealBrandCityList.size();i++){
                list.add(unequealBrandCityList.get(i));
                if(i == 0 & preIsEqueals){
                    ids.add("'"+((Map)unequealBrandCityList.get(i)).get("id")+"'");
                }
                else {
                    ids.add(",'"+((Map)unequealBrandCityList.get(i)).get("id")+"'");
                }

            }

        // 再加入所有list（去除以上已加入的list）
        List allOrganList = getAllOrgan(ids,longt,latit);
        for(int i = 0;i<allOrganList.size();i++){
            list.add(allOrganList.get(i));
        }

        return list;
    }

    /**
     * @Name: 通过vin查询上次保养车辆
     * @Author: Liu XiaoLong
     * @Date: 2017/10/25 10:31
     * @Remark:
     */
    @Override
    public Map getLastOrganByVin(String uid, String vin) throws Exception {
        if(vin.isEmpty()){
            throw new Exception("请输入正确的vin！");
        }
        String sql = "SELECT id, o_address, o_name, o_phone, longtitude, latitude FROM t_bc_organ WHERE ";
        sql += "id = ( SELECT company_id FROM t_crm_car_workorder WHERE vin = ? ORDER BY balance_date DESC LIMIT 0, 1 ) AND o_type = '1' ";

        List params = new ArrayList();
        params.add(vin);
        return itBcOrganDao.info(sql,params.toArray());
    }

    /**
     * @Name: 获取所有门店
     * @Author: Liu XiaoLong
     * @Date: 2017/10/26 09:26
     * @Remark:
     */
    @Override
    public List getAllOrgan(String uid) throws Exception {
        String sql = "SELECT id, o_address, o_name, o_phone, longtitude, latitude FROM t_bc_organ where o_type = '1' ";
        return itBcOrganDao.list(sql);
    }

    /**
     * @Name: 获取上次保养门店信息，如果没有或者不在一个城市 返回map.size() == 0
     * @Author: Liu XiaoLong
     * @Date: 2017/10/24 14:03
     * @Remark:
     */
    private Map getLastOrgan(String vin,String city) throws Exception{
        String sql = "SELECT id,o_address,o_name,o_phone,dept_id,longtitude,latitude FROM t_bc_organ WHERE o_type='1' AND id = ( ";
        sql += "SELECT company_id FROM t_crm_car_workorder WHERE vin = ? ORDER BY balance_date DESC LIMIT 0,1 ) ";
        sql += "AND  (o_name LIKE ? OR o_address LIKE ? ) ";
        List params = new ArrayList();
        params.add(vin);
        params.add("%"+city+"%");
        params.add("%"+city+"%");
        return itBcOrganDao.info(sql,params.toArray());

    }
    /**
     * @Name: 同城市同品牌下的所有Organ
     * @Author: Liu XiaoLong
     * @Date: 2017/10/24 16:24
     * @Remark: 已经通过 id 去除Organ 并通过距离排序
     */
    private List getBrandCityOrgan(String vin,String city,String id,double longtitude,double latitude) throws Exception{

        String brand = "";

        /**通过vin查询车辆品牌**/
        String getBrandSql = "SELECT brand FROM t_crm_car WHERE vin = ? ";
        List getBrandParams = new ArrayList();
        getBrandParams.add(vin);
        Map info = itBcOrganDao.info(getBrandSql,getBrandParams.toArray());
        if(info.size()>0){
            brand = info.get("brand").toString();
        }


        String sql = "SELECT id,o_address,o_name,o_phone,dept_id,longtitude,latitude FROM t_bc_organ WHERE  o_type='1' ";
        List params = new ArrayList();
        if(!brand.isEmpty()){
            sql += "AND o_car_brand = ?  ";
            params.add(brand);
        }
        sql += "AND  (o_name LIKE ? OR o_address LIKE ? ) ";
        params.add("%"+city+"%");
        params.add("%"+city+"%");
        if(!id.isEmpty()){
            sql += " AND id NOT IN (?) ";
            params.add(id);
        }

        List list = itBcOrganDao.list(sql,params.toArray());
        return getNewListDESC(list,longtitude,latitude);
    }
    /**
     * @Name: 获取同一城市不同品牌的门店
     * @Author: Liu XiaoLong
     * @Date: 2017/10/24 17:35
     * @Remark: 已通过ID去重
     */
    private List getCityAndUnequalBrandOrgan(String city,List ids,double longtitude,double latitude) throws  Exception{
            String idsString = "";
            for(int i = 0;i<ids.size();i++){
                idsString += ids.get(i);
            }

            String sql = "SELECT id,o_address,o_name,o_phone,dept_id,longtitude,latitude FROM t_bc_organ WHERE  o_type='1' AND";
            sql += "(o_name LIKE ? OR o_address LIKE ? ) ";
            if(!idsString.isEmpty()){
                sql += " AND id NOT IN ( "+idsString+" ) ";
            }
            List params = new ArrayList();
            params.add("%"+city+"%");
            params.add("%"+city+"%");
            List list = itBcOrganDao.list(sql,params.toArray());
            return getNewListDESC(list,longtitude,latitude);
    }

    /**
     * @Name: 获取所有门店
     * @Author: Liu XiaoLong
     * @Date: 2017/10/25 09:29
     * @Remark:  已通过id去重
     */
    private List getAllOrgan(List ids,double longtitude,double latitude) throws Exception{
        String idsString = "";
        for(int i = 0;i<ids.size();i++){
            idsString += ids.get(i);
        }
        String sql = "SELECT id,o_address,o_name,o_phone,dept_id,longtitude,latitude FROM t_bc_organ WHERE o_type='1' ";
        if(!idsString.isEmpty()){
            sql += "AND id NOT IN ( "+idsString+" ) ";
        }
        List list = itBcOrganDao.list(sql);
        return getNewListDESC(list,longtitude,latitude);
    }

    /**
     * @Name: 根据距离重新排序list
     * @Author: Liu XiaoLong
     * @Date: 2017/10/24 16:55
     * @Remark:
     */
    private List getNewListDESC(List list,double longtitude,double latitude){
        //String sql = "select id,o_address,o_name,o_phone,latitude,longtitude from "+tableName+" " ;
        //list.add(itBcOrganDao.list(sql));

        for(int i = list.size()-1;i>0;i--){
            for(int j=1;j<=i;j++){
                Map map0 = (Map) list.get(j-1);
                Map map1 = (Map) list.get(j);
                double a0 = getM(longtitude,latitude,Double.parseDouble(map0.get("longtitude").toString()),Double.parseDouble(map0.get("latitude").toString()));
                double a1 = getM(longtitude,latitude,Double.parseDouble(map1.get("longtitude").toString()),Double.parseDouble(map1.get("latitude").toString()));
                if(a0>a1){
                    list.set((j-1),map1);
                    list.set((j),map0);
                }
            }
        }
        return list;
    }
    /**
     * @Name: 获取两点距离 根据经度纬度
     * @Author: Liu XiaoLong
     * @Date: 2017/10/23 17:51
     * @Remark:
     */
    private static double getM(double longtitude1,double latitude1,double longtitude2,double latitude2){
        double EARTH_RADIUS = 6378.137 * 1000;//地球半径以米为单位

        double radLat1 = rad(latitude1);
        double radLat2 = rad(latitude2);
        double a = radLat1 - radLat2;
        double b = rad(longtitude1) - rad(longtitude2);

        double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a/2),2) +
                Math.cos(radLat1)*Math.cos(radLat2)*Math.pow(Math.sin(b/2),2)));
        s = s * EARTH_RADIUS;
        s = Math.round(s * 10000) / 10000;
        //System.out.println(s);
        return s;
    }
    /**
     * @Name: 角度换算为弧度
     * @Author: Liu XiaoLong
     * @Date: 2017/10/23 17:45
     * @Remark:
     */
    private static double rad(double d)
    {
        return d * Math.PI / 180.0;
    }
}
